package com.avoid.easymqtt.mqtt.protocol;

import com.avoid.easymqtt.mqtt.MqttRequestProcessor;
import com.avoid.easymqtt.mqtt.common.MqttNettyUtils;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.mqtt.MqttConnAckMessage;
import io.netty.handler.codec.mqtt.MqttConnectMessage;
import io.netty.handler.codec.mqtt.MqttConnectReturnCode;
import io.netty.handler.codec.mqtt.MqttMessage;
import io.netty.handler.codec.mqtt.MqttProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 客户端到服务端的网络连接建立后，客户端发送给服务端的第一个报文必须是CONNECT报文
 *
 * @author avoid@fiture.com
 * @date 2022/5/9
 * @motto Life is so short,do something to make yourself happy,such as coding
 */
public class ConnectProcessor implements MqttRequestProcessor {
    private static final Logger log = LoggerFactory.getLogger(ConnectProcessor.class);

    @Override
    public MqttMessage processRequest(ChannelHandlerContext ctx, MqttMessage msg) throws Exception {
        MqttConnectMessage connectMessage = (MqttConnectMessage)msg;
        MqttConnectReturnCode returnCode;
        int mqttVersion = connectMessage.variableHeader().version();
        String clientId = connectMessage.payload().clientIdentifier();
        if (!versionValid(mqttVersion)) {
            returnCode = MqttConnectReturnCode.CONNECTION_REFUSED_UNSUPPORTED_PROTOCOL_VERSION;
        } else {
            // TODO 处理连接
            returnCode = MqttConnectReturnCode.CONNECTION_ACCEPTED;
        }

        if (returnCode != MqttConnectReturnCode.CONNECTION_ACCEPTED) {
            ctx.close();
            log.warn("[CONNECT] -> {} 连接失败，返回代码={}", clientId, returnCode);
        }
        // 设置clientId
        MqttNettyUtils.clientID(ctx.channel(), clientId);
        return MqttMessageFactory.getConnectAckMessage(returnCode, true, null);
    }

    @Override
    public boolean rejectRequest() {
        return false;
    }

    private boolean versionValid(int mqttVersion) {
        return mqttVersion == 3 || mqttVersion == 4 || mqttVersion == 5;
    }
}
